var util = {};

function setUtil(obj) {
    util = obj;
}

//视频 
var videoObj = {
    isplayingObj: {},
    VidoeAd: null,
    adUnitId: "",
    playOne: function (adUnitId, succ, err) {
        //看视频就暂停音乐
        Laya.SoundManager.stopAll();

        // window.rewordResult = function (tag) {
        //     if (tag) {
        //         if (succ) {
        //             succ();
        //         }
        //     } else {
        //         window.currPage.showClew("视频加载失败，请稍后再试~");
        //         if (err) {
        //             err();
        //         }
        //     }
        // }
        // bridgeObjCall("showReward");
        // return;

        if (!util.iswx) {
            // window.currPage.showClew("视频加载失败，请稍后再试~");
            if (succ) {
                succ();
            }
            return;
        }
        if (!util.wx.createRewardedVideoAd) {
            // util.gobackmuc();
            window.currPage.showClew("视频加载失败，请稍后再试~");
            if (err) {
                err();
            }
            return;
        }
        adUnitId = "adunit-52c5be054b2c7b98";
        //播放中
        if (videoObj.isplayingObj[adUnitId]) {
            return;
        }
        videoObj.isplayingObj[adUnitId] = true;
        console.log("加载播放adUnitId", adUnitId);
        this.playCallsucc = function () {
            videoObj.isplayingObj[adUnitId] = false;
            // util.gobackmuc();
            if (succ) {
                succ();
            }
        };
        this.playCallErr = function (types) {
            videoObj.isplayingObj[adUnitId] = false;
            if (types == "close") {
                window.currPage.showClew("广告播放失败，要看完哦~");
            } else {
                window.currPage.showClew("视频加载失败，请稍后再试~");
            }
            // util.gobackmuc();
            if (err) {
                err(types);
            }
        };

        // 创建激励视频广告实例，提前初始化
        if (!this.VidoeAd) {
            this.VidoeAd = wx.createRewardedVideoAd({
                adUnitId: adUnitId
            });
            this.VidoeAdError1 = function (res) {
                if (res && res.isEnded || res === undefined) {
                    // 正常播放结束，可以下发游戏奖励
                    videoObj.playCallsucc();
                } else {
                    // 播放中途退出，不下发游戏奖励
                    videoObj.playCallErr("close");
                }
            }
            this.VidoeAdError2 = function () {
                videoObj.playCallErr("error");
            }
        }
        var videoAd = this.VidoeAd;
        videoAd.offError(this.VidoeAdError2);
        videoAd.onError(this.VidoeAdError2);

        videoAd.offClose(this.VidoeAdError1);
        videoAd.onClose(this.VidoeAdError1);

        // 用户触发广告后，显示激励视频广告
        videoAd.show().catch(function (err) {
            videoAd.load().then(function () {
                videoAd.show();
            });
        });
    }
};


var adunitArr = ["adunit-05681fa0877b4f44"];
var newadunitObj = {};
for (var i = 0; i < adunitArr.length; i++) {
    newadunitObj[adunitArr[i]] = true;
}

//广告对象
var guanggaobannObj = {
    bannheight: 100, //默认高度
    getBnnTop: -1, //y的位置
    bannerAdResize: function () {
        var parent = this;
        console.log("bannerAdResize");
        //获取banner尺寸 横版不需要 竖版需要
        var offtop = util.isiphoneX ? 45 : 0;
        offtop = 0; //横版不需要 竖版需要
        //onshow回来后，更新一下当前位置省的错位
        for (var i in this.bannCacheObj) {
            var loadbannObj = this.bannCacheObj[i];
            if (loadbannObj.show) {
                var y = util.sys.height - guanggaobannObj.bannheight - 2; //不底对齐 留一些
                loadbannObj.style.y = y;
                loadbannObj.banner.style.top = y;
                // setTimeout(function () {
                //     if (loadbannObj && loadbannObj.banner) {
                //         loadbannObj.banner.style.top = loadbannObj.style.y;
                //         console.log(111, loadbannObj.style.y);
                //     }
                // }, 500);
                console.log(util.sys.height, guanggaobannObj.bannheight, y);
            }
        }
    },
    setPathBann: function (type) {
        //设置位置
        var parent = this;
        //onshow回来后，更新一下当前位置省的错位
        for (var i in this.bannCacheObj) {
            var bannerobj = this.bannCacheObj[i];
            if (bannerobj.show) {
                var sw = guanggaobannObj.getBannW(); //  300; // parseInt(util.sys.width * 0.8); //默认宽度
                var xs = (util.sys.width - bannerobj.style.w) / 2; //默认居中
                if (type == "big") {
                    //宽度全屏
                    sw = parseInt(util.sys.width);
                } else if (type == "right") {
                    //右对齐
                    xs = util.sys.width - bannerobj.style.w; //右对齐
                }
                //检测是否不一样
                if (bannerobj.style.w != sw) {
                    bannerobj.style.w = sw;
                    bannerobj.banner.style.width = bannerobj.style.w;
                }
                if (bannerobj.style.x != xs) {
                    bannerobj.style.x = xs;
                    bannerobj.banner.style.left = bannerobj.style.x;
                }
                parent.bannheight = bannerobj.style.h;
                parent.getBnnTop = bannerobj.style.y;
                console.log("bannheight:", parent.bannheight);
            }
        }

    },
    currShowBannid: "", //当前显示的bannerid
    bannertype: "hide",
    bannCacheObj: {}, //banner保存的
    getSizeBann: function (loadbannObj, obj) {
        var sw = util.sys.width;
        if (obj.width > sw) {
            obj.width = sw;
        }
        //获取banner尺寸
        var offtop = util.isiphoneX ? 60 : 0;
        offtop = 0; //横版不需要 竖版需要

        loadbannObj.style.w = obj.width;
        loadbannObj.style.h = obj.height;
        loadbannObj.style.x = (util.sys.width - loadbannObj.style.w) / 2;
        loadbannObj.style.y = util.sys.height - loadbannObj.style.h - offtop - 2; //不底对齐 留一些
        if (loadbannObj.loadok) {
            loadbannObj.banner.style.left = loadbannObj.style.x;
            loadbannObj.banner.style.top = loadbannObj.style.y;
        }
        if (this.currShowBannid == loadbannObj.id) {
            this.bannheight = loadbannObj.style.h;
            this.getBnnTop = loadbannObj.style.y;
            console.log("bannheight:", this.bannheight);
        }
    },
    getCurrBannid: function (type) {
        //排序找到一个展示最少的
        var parent = this;
        var arr = [];
        for (var i in this.bannCacheObj) {
            arr.push({
                id: i,
                num: this.bannCacheObj[i].num
            });
        }
        arr.sort(function (a, b) {
            return a.num < b.num ? -1 : 1;
        });
        var callback = function (bannerobj, cachetype) {
            if (parent.currShowBannid == bannerobj.id) {
                if (!bannerobj.show) {
                    //显示
                    bannerobj.show = true;
                    bannerobj.num++;
                    bannerobj.banner.show();
                }
                var sw = guanggaobannObj.getBannW(); //  300; // parseInt(util.sys.width * 0.8); //默认宽度
                var xs = (util.sys.width - bannerobj.style.w) / 2; //默认居中
                if (type == "big") {
                    //宽度全屏
                    sw = parseInt(util.sys.width);
                } else if (type == "right") {
                    //右对齐
                    xs = util.sys.width - bannerobj.style.w; //右对齐
                }
                //检测是否不一样
                if (bannerobj.style.w != sw) {
                    bannerobj.style.w = sw;
                    bannerobj.banner.style.width = bannerobj.style.w;
                }
                if (bannerobj.style.x != xs) {
                    bannerobj.style.x = xs;
                    bannerobj.banner.style.left = bannerobj.style.x;
                }
                parent.bannheight = bannerobj.style.h;
                parent.getBnnTop = bannerobj.style.y;
                console.log("bannheight:", parent.bannheight);
            } else {
                console.log("加载不显示");
            }
        }
        console.log("arr:", arr);
        if (arr.length == 0) {
            //默认加载完毕就显示
            this.currShowBannid = this.getOneBann(callback, true);
        } else {
            console.log("使用id:", arr[0].id);
            var loadbannObj = this.bannCacheObj[arr[0].id];
            this.currShowBannid = arr[0].id;
            if (callback) {
                callback(loadbannObj);
            }
            this.getOneBann();
        }
    },
    getBannW: function () {
        var w = 300;
        if (util.isiphoneX) {
            // if (util.sys.height / util.sys.width <= 1.78) {
            w = util.sys.width;
        }
        return w;
    },
    getOneBann: function (callback) {
        var parent = this;
        var id = "";
        var idarr = [];
        //便利所有，找到当前不存在的
        for (var i in newadunitObj) {
            if (!this.bannCacheObj[i]) {
                idarr.push(i);
            }
        }
        if (idarr.length >= 1) {
            //随机一个新的bannerid
            console.log(idarr);
            id = idarr[parseInt(Math.random() * idarr.length)];
        }
        if (id == "") {
            console.log("id已满", this.bannCacheObj);
            return;
        }
        var sw = guanggaobannObj.getBannW(); // 300; // parseInt(util.sys.width * 0.8); //默认宽度
        var offtop = util.isiphoneX ? 60 : 0;
        offtop = 0; //横版不需要 竖版需要
        if (sw < 300) {
            sw = 300;
        }

        var loadbannObj = {
            id: id,
            num: 0,
            style: {},
            loadok: false,
            show: false,
            banner: null
        }
        this.getSizeBann(loadbannObj, {
            width: sw,
            height: this.bannheight
        });

        var objs = {
            adUnitId: id,
            "style": {
                left: loadbannObj.style.x,
                top: loadbannObj.style.y,
                width: loadbannObj.style.w,
            }
        }
        var banner = util.wx.createBannerAd(objs);
        loadbannObj.banner = banner;

        var load_fun = function () {
            //加载完毕销毁掉
            //生成成功
            loadbannObj.loadok = true;
            if (loadbannObj.banner.style.left != loadbannObj.style.x) {
                loadbannObj.banner.style.left = loadbannObj.style.x;
            }
            if (loadbannObj.banner.style.top != loadbannObj.style.y) {
                loadbannObj.banner.style.top = loadbannObj.style.y;
            }
            if (callback) {
                callback(loadbannObj);
            }
            //取消事件
            banner.offLoad(load_fun);
            banner.offError(err_fun);
        }
        var err_fun = function () {
            //加载失败
            loadbannObj.clear();
        }
        var resize_fun = function (obj) {
            //组件尺寸发生改变时
            parent.getSizeBann(loadbannObj, obj);
        }
        banner.onResize(resize_fun);
        banner.onError(err_fun);
        banner.onLoad(load_fun);
        loadbannObj.clear = function () {
            banner.offLoad(load_fun);
            banner.offError(err_fun);
            banner.offResize(resize_fun);
            delete parent.bannCacheObj[id];
        }
        parent.bannCacheObj[id] = loadbannObj;
        return id;
    },
    openBanner: function (tag) {
        var parent = this;
        // bridgeObjCall("showAdBanner", true);

        if (!util.iswx) {
            return;
        }
        if (!util.wx.createBannerAd) {
            return;
        }
        var time = Date.now();
        if (this.bannertype != "show") {
            this.bannertype = "show";
            this.getCurrBannid(tag);

            if (tag == "right") {
                this.bannertypeisright = true;
            } else {
                this.bannertypeisright = false;
            }
            this.bannertypetime = time;
            clearTimeout(this.bannertypeisrightT);

            console.log("openbanner");
            if (this.bannertypeisright) {
                this.bannertypeisrightT = setTimeout(function () {
                    parent.bannertypetime = time;
                    parent.setPathBann();
                    parent.bannertypeisright = false;
                }, 1000);
            }

            if (tag == "hideload") {
                this.hideBanner();
            }
        } else {
            // if (this.bannertypeisright) {
            //     if (time - this.bannertypetime >= 800) {
            //         this.bannertypetime = time;
            //         this.setPathBann();
            //         this.bannertypeisright = false;
            //     }
            // }
        }
    },
    deleteCache: function (name) {
        //删除  
        this.bannCacheObj[name].clear();
        //        console.log("删除", name, this.bannCacheObj);
    },
    hideBanner: function (tag) {
        // bridgeObjCall("showAdBanner", false);

        if (!util.iswx) {
            return;
        }
        if (!util.wx.createBannerAd) {
            return;
        }
        if (this.bannertype != "hide") {
            this.bannertype = "hide";
            console.log("hidebanner");
            clearTimeout(this.bannertypeisrightT);
            //因此所有的banner
            this.currShowBannid = "";
            for (var i in this.bannCacheObj) {
                if (this.bannCacheObj[i].show) {
                    this.bannCacheObj[i].show = false;
                    this.bannCacheObj[i].banner.hide();
                    //删除
                    if (tag) {
                        //删除
                        this.deleteCache(i);
                    }
                }
            }
        }
    }
}

//调用打包的
var bridgeObj = null;
function bridgeObjCall(key1, key2) {
    if (typeof PlatformClass != "undefined") {
        if (!bridgeObj) {
            bridgeObj = PlatformClass.createClass("com.layabox.game.JSBridge");
        }
        if (key2 == undefined) {
            bridgeObj.call(key1);
        } else {
            bridgeObj.call(key1, key2);
        }
    }
}


//插屏广告
var chapingObj = {
    show: function () {
        // bridgeObjCall("showInner");
        if (!util.iswx) {
            return;
        }
        //插屏
        if (util.wx.createInterstitialAd) {
            var obj = util.wx.createInterstitialAd({
                adUnitId: "adunit-17c608f2de921d52"
            });
            obj.onLoad(function () {
                if (obj && obj.show) {
                    obj.show();
                }
            });
            obj.onError(function () {

            });
        }

    }
}


//格子
var gridAdObj = {
    gridAd: null,
    show: function () {
        if (this.gridAd) {
            this.gridAd.show();
        }
    },
    init: function () {

    }
}



//格子
var createCustomObj = {
    obj: null,
    obj1: null,
    show: function () {
        // if (this.obj) {
        //     this.obj.show();
        // }
        if (this.obj1) {
            this.obj1.show();
        }
    },
    init: function (w, ipx) {
        if (util.iswx && wx.createCustomAd) {
            var parent = this;
            /*
            // 单个格子广告实例，提前初始化
            this.obj = wx.createCustomAd({
                adUnitId: 'adunit-31f74787bc3151d3',
                adIntervals: 30,
                style: {
                    left: 10,
                    top: ipx ? 90 : 50,
                }
            });
            this.obj.onLoad(function () {

            });
            // 在适合的场景显示格子广告
            // this.gridAd.show();
            this.obj.onError(function () {

            });
            */

            // 单个格子广告实例，提前初始化
            this.obj1 = wx.createCustomAd({
                adUnitId: 'adunit-05c3c91e8c96ab2b',
                adIntervals: 30,
                style: {
                    left: w - 70,
                    top: ipx ? 120 : 70,
                }
            });
            // this.obj1.onResize(function (res) {
            //     parent.obj1.style.left = w - res.width - 10;
            //     console.log(111);
            // });

            this.obj1.onLoad(function () {
                // parent.obj1.show();
            });
            // 在适合的场景显示格子广告
            // this.gridAd.show();
            this.obj1.onError(function () {

            });
        }
    }
}


export default {
    setUtil: setUtil,
    createCustomObj: createCustomObj,
    gridAdObj: gridAdObj, //格子
    chapingObj: chapingObj, //插屏
    guanggaobannObj: guanggaobannObj, //广告banner
    videoObj: videoObj, //视频
}